package com.bidevalution.controller.api;

import com.bidevalution.business.service.*;
import com.bidevalution.controller.util.RequestUtil;
import com.bidevalution.dao.entity.*;
import com.bidevalution.support.context.Constants;
import com.bidevalution.support.exception.BizException;
import com.qtp.common.constants.SystemConstants;
import com.qtp.common.core.TSUser;
import com.qtp.common.data.RedisAccess;
import com.qtp.core.model.Response;
import com.qtp.core.util.OConvertUtils;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/beSectionExpertProgress")
@Api(tags = "评标进度管理")
public class BeSectionExpertProgressController extends BaseController{
	@Autowired
	private BeSectionExpertProgressService beSectionExpertProgressService;
	@Autowired
	private BeSectionExpertInfoService beSectionExpertInfoService;
	@Autowired
	private BeSectionStepService beSectionStepService;
	@Autowired
	private BeSectionInfoService beSectionInfoService;
	@Autowired
	private BeExpertAdviceSummaryService beExpertAdviceSummaryService;
	@Autowired
	private BeExpertAdviceService beExpertAdviceService;
	@Autowired
	BeExpertRecommendCandidateService recommendCandidateService;

	@ApiOperation(value = "查询当前专家环节是否完成评标", notes = "查询当前专家环节是否完成评标")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "sectionStepId", value = "环节ID", required = true, dataType = "String", paramType = "query") })
	@ApiResponses({
			@ApiResponse(code = Constants.FIVE_HUNDRED_AND_ONE, message = "未查询到该标段环节信息"),
			@ApiResponse(code = Constants.FIVE_HUNDRED_AND_TWO, message = "获取专家信息失败，请重新登录"),
			@ApiResponse(code = Constants.FIVE_HUNDRED_AND_THREE, message = "当前用户不是该标段专家")
	})
	@GetMapping("/getSectionExpertProgressFinish")
	public Response<Integer> selectById(@RequestParam("sectionStepId") String sectionStepId) throws Exception {
		String userGuid = RequestUtil.getHeader("userGuid");
		TSUser tsUser = RedisAccess.getValue(TSUser.class, userGuid);
		if (tsUser != null) {
			BeSectionStep beSectionStep = beSectionStepService.getSectionStepBySeqId(sectionStepId);
			if (beSectionStep == null) {
				throw new Exception("未查询到该标段环节信息");
			}
			BeSectionExpertInfo beSectionExpertInfo = beSectionExpertInfoService.selectByLoginName(beSectionStep.getSectionId(), tsUser.getLoginName());
			if(beSectionExpertInfo == null) {
				throw new Exception("当前用户不是该标段专家");
			}
			return Response.ok(beSectionExpertProgressService.getFinishStatus(sectionStepId,beSectionExpertInfo.getSeqId()));
		} else {
			return Response.fail("获取专家信息失败，请重新登录", Constants.FIVE_HUNDRED_AND_TWO);
		}
	}
	@ApiOperation(value = "查询所有环节是否完成评标", notes = "查询所有环节是否完成评标")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "sectionStepId", value = "环节ID", required = true, dataType = "String", paramType = "query") })
	@GetMapping("/getSectionStepProgressFinish")
	public Response<Integer> selectAllStep(@RequestParam("sectionStepId") String sectionStepId) throws Exception {
		try {
			Boolean flagBoolean = beSectionExpertProgressService.getFinishStatus(sectionStepId);
			if(flagBoolean) {
				return Response.ok(1);
			}
		}catch (Exception e) {
			return Response.fail("操作失败");
		}
		return Response.ok(0);
	}
	@ApiOperation(value = "查询专家列表", notes = "查询专家列表")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "sectionStepId", value = "环节ID", required = true, dataType = "String", paramType = "query") })
	@GetMapping("/getSectionExpertProgressList")
	public Response<List<BeSectionExpertProgress>> selectList(@RequestParam("sectionStepId") String sectionStepId)
			throws Exception {
		return Response.ok(beSectionExpertProgressService.selectList(sectionStepId));
	}
	@ApiOperation(value = "环节回退", notes = "环节回退")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "sectionId", value = "项目id", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "stepCode", value = "环节代码", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "backStepCode", value = "回退环节代码", required = true, dataType = "String", paramType = "query")})
	@PostMapping("/updateStepStatus")
	public Response<String> updateProgressListStatus(@RequestParam("sectionId") String sectionId,@RequestParam("stepCode") String stepCode,@RequestParam("backStepCode") String backStepCode)
			throws Exception {
		try {
			beSectionExpertProgressService.updateStatus(sectionId, stepCode,"0");
			beSectionExpertProgressService.updateStatus(sectionId, backStepCode,"0");
			return Response.ok("操作成功");
		}catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return Response.fail("操作失败");
	}


	@ApiOperation(value = "查询专家列表(用于评审结束按钮)", notes = "查询专家列表(用于评审结束按钮)")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "sectionStepId", value = "环节ID", required = true, dataType = "String", paramType = "query")})
	@GetMapping("/querySectionExpertProgressList")
	@ApiResponses({
			@ApiResponse(code = Constants.FIVE_HUNDRED_AND_ONE, message = "参数不可以为空！"),
			@ApiResponse(code = Constants.FIVE_HUNDRED_AND_TWO, message = "系统异常，请联系管理员！"),
			@ApiResponse(code = Constants.FIVE_HUNDRED_AND_THREE, message = "获取专家账号登录信息失败，请重新登录！"),
	})
	public Response<List<BeSectionExpertProgress>> querySectionExpertProgressList(@RequestParam("sectionStepId") String sectionStepId, HttpServletRequest request) {
		if (StringUtils.isBlank(sectionStepId)) {
			return Response.fail("参数不可以为空！", Constants.FIVE_HUNDRED_AND_ONE);
		}
		String userGuid = RequestUtil.getHeader("userGuid");
		TSUser tsUser = RedisAccess.getValue(TSUser.class, userGuid);
		if (tsUser == null) {
			return Response.fail("获取专家账号登录信息失败，请重新登录！", Constants.FIVE_HUNDRED_AND_THREE);
		}
		try {
			List<BeSectionExpertProgress> dataList = beSectionExpertProgressService.selectList(sectionStepId);
			if (dataList != null && !dataList.isEmpty()) {
				String sectionId = dataList.get(0).getSectionId();
				synchronized ((sectionId + "querySectionExpertProgressList").intern()) {
					//状态为3表示已经评审结束
					if (Constants.THREE.equals(beSectionInfoService.getBeSectionInfoById(sectionId).getReviewState())) {
						return Response.ok(dataList);
					}
					List<String> strList = new ArrayList<>();
					//循环获取到此环节的是否完成状态
					for (BeSectionExpertProgress beSectionExpertProgress : dataList) {
						strList.add(beSectionExpertProgress.getIsFinish());
					}
					//判断是否存在未完成状态，不存在则说明专家都已经提交
					if (!strList.contains(Constants.ZERO.toString())) {
						log.info("querySectionExpertProgressList()方法被调用");
						log.info("sectionId[" + sectionId + "]sectionStepId[" + sectionStepId + "]");
						//删除组长评审意见、专家废标说明和中标候选人列表(评审结束之后专家有可能重评，分担重评的删除数据压力，故放在此处)
						beSectionExpertProgressService.deleteExpertData(sectionId);
						if (!beSectionInfoService.updateSectionInfoById(sectionId)) {
							throw new Exception("更新标段评审状态失败！");
						}
						Response<BeExpertAdviceSummary> res3 = beExpertAdviceSummaryService.getBeExpertAdviceSummary(sectionId);
						if (Constants.FIVE_HUNDRED == res3.getStatus()) {
							log.error("获取组长评审意见失败，失败信息[" + res3.getError() + "]");
						}
						Map<String, Object> params = new HashMap<>(4);
						for (BeSectionExpertInfo beSectionExpertInfo:beSectionExpertInfoService.getListBySectionId(sectionId,Constants.STR_NO)) {
							params.put("sectionId", sectionId);
							params.put("loginName", beSectionExpertInfo.getLoginName());
							Response<BeExpertAdvice> res1 = beExpertAdviceService.getUnPassedInfo(params);
							if (Constants.FIVE_HUNDRED == res1.getStatus()) {
								log.error("获取专家废标说明失败，失败信息[" + res1.getError() + "]");
							}
							Response<List<BeExpertRecommendCandidate>> res2 = recommendCandidateService.getRecommendCandidateList(params);
							if (Constants.FIVE_HUNDRED == res2.getStatus()) {
								log.error("获取中标候选人列表失败，失败信息[" + res2.getError() + "]");
							}
						}
					}
				}
			}
			return Response.ok(dataList);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return Response.fail("系统异常，请联系管理员！", Constants.FIVE_HUNDRED_AND_TWO);
		}
	}
}
